<script lang="tsx" setup>
import { computed, reactive, ref, watch } from 'vue';
import { type FormRules, NAvatar, NText } from 'naive-ui';
import type { DeptVO } from '@/service/types/system';
import { getAllUsers } from '@/service/api/system/user';
import { addDept, editDept, getDept } from '@/service/api/system/dept';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import type { DictDataOption } from '@/typings/global';
type Model = Pick<
  DeptVO,
  'deptName' | 'deptCategory' | 'parentId' | 'status' | 'orderNum' | 'leader' | 'phone' | 'email'
>;
interface Props {
  operateType: NaiveUI.TableOperateType;
  currentId?: string | number | null | unknown;
  depts: DeptVO[];
  sysNormalDisable: DictDataOption[];
}
const options = ref([]);
const loading = ref(false);
const optionLoading = ref(false);
interface Emits {
  (e: 'submitted'): void;
}
const show = ref<boolean>(false);
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
defineOptions({
  name: 'DeptForm'
});
const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const rules: FormRules = {
  parentId: createRequiredRule('上级部门不能为空'),
  orderNum: createRequiredRule('显示顺序不能为空'),
  deptName: {
    required: true,
    min: 1,
    max: 30,
    message: '部门称长度必须介于 1 和 30 之间',
    trigger: 'blur'
  },
  deptCategory: {
    required: false,
    min: 1,
    max: 100,
    message: '部门类别编码称长度必须介于 1 和 100 之间',
    trigger: 'change'
  }
};

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增部门',
    edit: '修改部门'
  };
  return titles[props.operateType];
});
const visible = defineModel<boolean>('visible', {
  default: false
});
const currentModelData = ref<DeptVO>();
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    status: '0',
    deptName: '',
    parentId: '',
    deptCategory: '',
    orderNum: 0,
    phone: '',
    email: '',
    leader: null
  };
}
const getDeptById = async (id: number) => {
  show.value = true;
  const { error, data } = await getDept(id);
  if (!error) {
    currentModelData.value = data?.data;
  }
  show.value = false;
};

const handleGetUserList = async () => {
  optionLoading.value = true;
  const { data, error } = await getAllUsers();
  optionLoading.value = false;
  if (!error) {
    options.value = data?.data;
  }
};
async function handleInitModel() {
  Object.assign(model, createDefaultModel());
  if (props.operateType === 'edit' && props.currentId) {
    // Object.assign(model, props.rowData);
    // const data = await featchGetInfo();
    await getDeptById(props.currentId as number);
    // featchPost(data.deptId);
    Object.assign(model, currentModelData.value);
  }
}
watch(visible, () => {
  if (visible.value) {
    handleGetUserList();
    handleInitModel();
    restoreValidation();
  }
});

const renderLabel = (option: { avatar: any; userName: any; email: any }) => {
  return (
    <div class="flex flex-items-center">
      <NAvatar size="small" round src={option.avatar} />
      <div class="ml-12px" style="padding:4px 0px">
        <div>{option.userName}</div>
        <NText depth="3" tag="div">
          {option.email}
        </NText>
      </div>
    </div>
  );
};

const renderSingleSelectTag = ({ option }) => {
  return (
    <div class="flex flex-items-center">
      <NAvatar size={24} class="mr-10px" round src={option.avatar} />
      {option.userName}
    </div>
  );
};

const closeModal = () => {
  visible.value = false;
};
const submitAddDept = async (params: DeptVO) => {
  const { error, data } = await addDept(params);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    closeModal();
    emit('submitted');
  }
};
const submitEditDept = async (params: DeptVO) => {
  const { error, data } = await editDept(params);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    closeModal();
    emit('submitted');
  }
};
async function handleSubmit() {
  await validate();
  loading.value = true;
  const { ...params } = model;
  if (!props.currentId) {
    await submitAddDept(params as DeptVO);
  } else {
    await submitEditDept({ ...params, deptId: props.currentId } as DeptVO);
  }
}
const handleSelectLeader = (value: any, option: any) => {
  // const data = JSON.parse(JSON.stringify(option));
  model.email = option?.email;
  model.phone = option?.phonenumber;
};
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-740px">
    <NSpin :show="show">
      <NForm ref="formRef" :model="model" :rules="rules">
        <NGrid x-gap="12" responsive="screen" item-responsive>
          <NFormItemGi v-if="model.parentId !== 0" span="24 s:12 m:12" label="上级部门" path="parentId">
            <NTreeSelect
              v-model:value="model.parentId"
              label-field="deptName"
              filterable
              key-field="deptId"
              :options="props.depts"
            />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="部门名称" path="deptName">
            <NInput v-model:value="model.deptName" placeholder="请输入部门名称" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="类别编码" path="deptCategory">
            <NInput v-model:value="model.deptCategory" placeholder="请输入类别编码" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="排序" path="orderNum">
            <NInputNumber
              v-model:value="model.orderNum"
              :min="0"
              :max="9999"
              class="w-100%"
              clearable
              placeholder="排序"
            />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="负责人" path="leader">
            <NSelect
              v-model:value="model.leader"
              label-field="userName"
              value-field="userId"
              :options="options"
              placeholder="请选择负责人"
              clearable
              :loading="optionLoading"
              :render-label="renderLabel"
              :render-tag="renderSingleSelectTag"
              @update:value="handleSelectLeader"
            />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="电话" path="phone">
            <NInput v-model:value="model.phone" placeholder="请输入手机号" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="邮箱" path="email">
            <NInput v-model:value="model.email" placeholder="请输入邮箱" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="状态" path="status">
            <NRadioGroup v-model:value="model.status">
              <NRadioButton v-for="(item, index) in props.sysNormalDisable" :key="index" :value="item.value">
                {{ item?.label }}
              </NRadioButton>
            </NRadioGroup>
          </NFormItemGi>
        </NGrid>
      </NForm>
    </NSpin>

    <template #footer>
      <NSpace justify="end">
        <NButton @click="closeModal">取消</NButton>
        <NButton type="primary" :loading="loading" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped></style>
